<style scoped>
.three-canvas {
  width: 100%;
  height: 100%;
  display: block;
}
</style>

<template><canvas class="three-canvas" ref="canvas"></canvas></template>

<script>
const threeSceneMap = new Map()
const getSceneByName = (sceneName) => {
  return threeSceneMap.get(sceneName)
}
const setSceneByName = (sceneName, scene) => {
  if (threeSceneMap.has(sceneName)) {
    throw new Error(`场景${sceneName}已经存在`)
  }
  threeSceneMap.set(sceneName, scene)
}
export { getSceneByName, setSceneByName }
</script>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue'
import { emit, THREE_SCENE_INITIALIZATION } from '../../utils/EventBus.js'
import { initScene } from './frame.js'

const canvas = ref(null)
const { sceneName, contextOptions } = defineProps({
  sceneName: {
    type: String,
    required: true,
  },
  contextOptions: {
    type: Object,
    default: () => ({}),
  },
})

onMounted(() => {
  const scene = initScene({ canvas: canvas.value, ...contextOptions })
  setSceneByName(sceneName, scene)
  if (sceneName === 'threeScene') {
    window.threeScene = scene
  }
  emit(THREE_SCENE_INITIALIZATION, { sceneName })
})
onBeforeUnmount(() => {
  const scene = getSceneByName(sceneName)
  if (scene) {
    scene.my.destroy()
    threeSceneMap.delete(sceneName)
  }
})




</script>
